const db = require('../db');

/**
 * Material Model
 */
const Material = {
    // 获取所有材料
    async getAll() {
        const [rows] = await db.execute('SELECT * FROM materials WHERE status != 2 ORDER BY id DESC');
        return rows;
    },

    // 按ID获取
    async getById(id) {
        const [rows] = await db.execute('SELECT * FROM materials WHERE id = ? AND status != 2', [id]);
        return rows[0];
    },

    // 创建
    async create(data) {
        const sql = `
      INSERT INTO materials 
      (name, code, specification, supplier, project, warehouse, type, amount_change, purchase_time, payment_time, cost, unit, rate, purchaser, remark, unit_price, paid, other_fee)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;
        const [result] = await db.execute(sql, [
            data.name, data.code, data.specification, data.supplier, data.project, data.warehouse, data.type,
            JSON.stringify(data.amount_change || {}), data.purchase_time, data.payment_time, data.cost,
            data.unit, data.rate, data.purchaser, data.remark, data.unit_price, data.paid, data.other_fee
        ]);
        return result.insertId;
    },

    // 更新
    async update(id, data) {
        const sql = `
      UPDATE materials 
      SET name=?, code=?, specification=?, supplier=?, project=?, warehouse=?, type=?, amount_change=?, 
          purchase_time=?, payment_time=?, cost=?, unit=?, rate=?, purchaser=?, remark=?, unit_price=?, 
          paid=?, other_fee=?, updated_at=NOW()
      WHERE id=?
    `;
        const [result] = await db.execute(sql, [
            data.name, data.code, data.specification, data.supplier, data.project, data.warehouse, data.type,
            JSON.stringify(data.amount_change || {}), data.purchase_time, data.payment_time, data.cost,
            data.unit, data.rate, data.purchaser, data.remark, data.unit_price, data.paid, data.other_fee, id
        ]);
        return result.affectedRows;
    },

    // 软删除
    async delete(id) {
        const [result] = await db.execute('UPDATE materials SET status = 2 WHERE id = ?', [id]);
        return result.affectedRows;
    }
};

module.exports = Material;
